package com.qf.team2.netdisc.interceptors;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 登录拦截器，查找cookie-username来判断用户是否登录
 *
 * @author QWER
 */
@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
public class LoginInterceptor implements HandlerInterceptor {
    private static final List<String> urls = new ArrayList<>();

    static {
        urls.add("login");
        urls.add("register");
    }

    public static boolean cookieValue(Cookie[] cookies) {

        return false;

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器已生效");
        StringBuffer requestURL = request.getRequestURL();
        for (String url : urls) {
            if (requestURL.toString().contains(url)) {
                return true;
            }
        }

        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                String value = cookie.getValue();
                System.out.println(value);
                if ("username".equals(cookie.getName())) {
                    return true;
                }
            }
        }
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write("您未登录");
        System.out.println("未放行");
        return false;
    }
}
